﻿using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api;
using Microsoft.AspNetCore.Mvc;
using Hospital.Utility.ZFB;
using Hospital.Model.Pay;
using Hospital.Utility.ApiResult;
using Aop.Api.Util;
using Hospital.IService;
using Microsoft.AspNetCore.Authorization;

namespace Hospital.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class PaymentController : ControllerBase
    {
        private readonly IOrderService _iOrderService;
        [HttpPost("/pay")]
        public ActionResult<ApiResult> Pay([FromBody] PayRequest payRequest)
        {
            DefaultAopClient client = new DefaultAopClient(
                config.GatewayUrl,
                config.AppId,
                config.PrivateKey,
                "json",
                "1.0",
                config.SignType,
                config.AlipayPublicKey,
                config.Charset,
                false
            );
            var timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff");
            var randomPart = new Random().Next(1000, 9999).ToString();
            string outTradeNo = timestamp + randomPart; // 模拟订单编号
            string subject = payRequest.Subject; // 从前端获取
            string totalAmount = payRequest.TotalAmount; // 从前端获取
            string body = payRequest.Body; // 从前端获取

            AlipayTradePagePayModel model = new AlipayTradePagePayModel
            {
                Body = body,
                Subject = subject,
                TotalAmount = totalAmount,
                OutTradeNo = outTradeNo,
                ProductCode = "FAST_INSTANT_TRADE_PAY"
            };

            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

            // 设置同步回调地址
            alipayRequest.SetReturnUrl("");

            // 设置异步通知接收地址
            alipayRequest.SetNotifyUrl("");

            // 将业务model载入到request
            alipayRequest.SetBizModel(model);

            AlipayTradePagePayResponse response = null;
            try
            {
                response = client.pageExecute(alipayRequest, null, "post");
                // 返回支付页面
                return ApiResultHelper.Success(new { PayPageHtml = response.Body });
            }
            catch (Exception ex)
            {
                // 处理异常
                return BadRequest(new { Error = ex.Message });
            }
        }

        //        {
        //    "trade_status": "TRADE_SUCCESS",
        //    "out_trade_no": "20150320010101001",
        //    "trade_no": "2014112611001004680073956707",
        //    "total_amount": 88.88,
        //    "seller_id": "2088102179239651",
        //    "buyer_id": "2088102179239651"
        //}


        [HttpPost("/notify")]
        public ActionResult payNotify(Dictionary<string, string> notifyParams)
        {
            // 从 notifyParams 获取支付结果相关信息
            string tradeStatus = notifyParams["trade_status"];
            string outTradeNo = notifyParams["out_trade_no"];
            string tradeNo = notifyParams["trade_no"];
            string sign = notifyParams["sign"];

            // 验证签名
            bool isSignValid = AlipaySignature.RSACertCheckV1(notifyParams, config.AlipayPublicKey, sign, "RSA2");
            if (!isSignValid)
            {
                return Content("error"); // 签名验证失败，直接返回
            }

            // 检查支付是否成功
            if (tradeStatus == "TRADE_SUCCESS")
            {
                // 支付成功，处理相关业务逻辑
                // 比如：更新订单状态，发送通知等
                return Content("success");
            }
            return Content("error");
        }
    }
}
